<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>btn-1</button>
    <button>btn-2</button>
    <button>btn-3</button>
    <button>btn-4</button>
    <button>btn-5</button>
    <hr>
    <button class="test">btn-1</button>
    <button class="test">btn-2</button>
    <button class="test">btn-3</button>
    <button class="test">btn-4</button>
    <button class="test">btn-5</button>
    <script>
        /**
         * 给每个按钮绑定事件，打印当前按钮的索引
         */

        //TODO step1: 获取按钮
        var btns = document.querySelectorAll('button');
        //TODO step2: 绑定事件
        for (var i = 0; i < btns.length; i++) {
            var btn = btns[i];
            btn.onclick = () => {
                console.log(i)
            }
        }

        // 此刻点击按钮，输出的一直是btns.length
        console.log(i) // 5
        /**
         * 分析:
         * 1. i此时是全局变量(1.可以在任何地方被访问 2.可以在任何地方被修改)
         */

        var btns2 = document.querySelectorAll('.test');
        for (let j = 0; j < btns2.length; j++) {
            var btn = btns2[j];
            btn.onclick = () => {
                console.log(j)
            }
        }

        console.log(j) // j is not defined
    </script>
</body>

</html>